<template>
    <textarea :id="id" placeholder="请输入"></textarea>
</template>

 <script setup>
import { onActivated, onMounted, onUnmounted, reactive, ref, watch } from "vue";

const props = defineProps({
    value: {
        type: String,
        default: "",
    },
    id: {
        type: String,
        default: function () {
            return (
                "vue-tinymce-" +
                +new Date() +
                ((Math.random() * 1000).toFixed(0) + "")
            );
        },
    },

    height: {
        type: Number,
        default: 600
    },

    readonly: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(['input'])

const state = reactive({
    hasChange: false,
    hasInit: false,
    fullscreen: false,
    editorData: null,
})

watch(() => props.value, (val) => {
    console.log(props.value, "组件接收的");
    state.editorData.setContent(props.value);
    if (!state.hasChange && state.hasInit) {
        nextTick(() =>
            tinymce.get(id).setContent(val || "")
        );
    }
});

onMounted(() => {
    console.log('On mounted');
    initTinymce()
})

onActivated(() => {
    console.log('onActivated');
    if (tinymce) {
        initTinymce()
    }
})

onUnmounted(() => {
    console.log("离开页面")
    destroyTinymce();
});



const initTinymce = () => {
    console.log(props.id, "ID的值")
    tinymce.init({
        selector: `#${props.id}`,
        language: 'zh_CN', //调用放在langs文件夹内的语言包
        toolbar: true, //隐藏工具栏
        menubar: false, //隐藏菜单栏
        readonly: props.readonly,//只读模式
        plugins: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount textpattern help emoticons autosave bdmap indent2em autoresize axupimgs kityformula-editor',
        toolbar: 'code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
    styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
    table image media charmap emoticons hr pagebreak insertdatetime print preview | fullscreen | bdmap indent2em lineheight axupimgs kityformula-editor',
        height: props.height, //编辑器高度
        min_height: props.height,
        /*content_css: [ //可设置编辑区内容展示的css，谨慎使用
            '/static/reset.css',
            '/static/ax.css',
            '/static/css.css',
        ],*/
        fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
        font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;',
        link_list: [
            { title: '预置链接1', value: 'http://www.tinymce.com' },
            { title: '预置链接2', value: 'http://tinymce.ax-z.cn' }
        ],
        image_list: [
            { title: '预置图片1', value: 'https://www.tiny.cloud/images/glyph-tinymce@2x.png' },
            { title: '预置图片2', value: 'https://www.baidu.com/img/bd_logo1.png' }
        ],
        image_class_list: [
            { title: 'None', value: '' },
            { title: 'Some class', value: 'class-name' }
        ],
        importcss_append: true,

        //自定义文件选择器的回调内容
        file_picker_callback(callback, value, meta) {
            if (meta.filetype === 'file') {
                callback('https://www.baidu.com/img/bd_logo1.png', { text: 'My text' });
            }
            if (meta.filetype === 'image') {
                callback('https://www.baidu.com/img/bd_logo1.png', { alt: 'My alt text' });
            }
            if (meta.filetype === 'media') {
                callback('movie.mp4', { source2: 'alt.ogg', poster: 'https://www.baidu.com/img/bd_logo1.png' });
            }
        },

        // 自定义图片上传
        images_upload_handler(blobInfo, success, failure) {
            let formData = new FormData();
            formData.append("file", blobInfo.blob());
            let config = {
                headers: { "Content-Type": "multipart/form-data" },
            }
            // axios.post('上传地址', formData, config).then((res) => {
            //     console.log(res, "上传图片")
            //     success(res.data.data.imgUrl);
            // }).catch((err) => {
            //     failure("上传失败！");
            // });
        },

        init_instance_callback: editor => {
            console.log(props.value, '组件加载结束')
            state.hasInit = true
            state.editorData = editor
            if (props.value) {
                editor.setContent(props.value)
            }

            editor.on('NodeChange Change KeyUp SetContent', () => {
                state.hasChange = true
                emit('input', editor.getContent())
            })
        },
        setup(editor) {
            editor.on('FullscreenStateChanged', (e) => {
                state.fullscreen = e.state
            })
        },
        toolbar_sticky: true,//粘性工具栏
        autosave_ask_before_unload: false,
    });
}

const destroyTinymce = () => {
    console.log(props.id, "销毁组件ID")
    const tinymces = tinymce.get(props.id)
    if (state.fullscreen) {
        tinymces.execCommand('mceFullScreen')
    }
    if (tinymces) {
        tinymces.destroy()
    }
}
</script>